<?php
// +----------------------------------------------------------------------
// | astp [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 网页授权
// +----------------------------------------------------------------------
namespace app\wewhat\controller;

use think\Controller;
use app\wewhat\service\HttpRequest;
use app\wewhat\service\Accesstoken;
use app\wewhat\model\Fxuser as fxuserModel;
use think\facade\Config;

class Warrant extends Controller
{
  // public function redirectUri()
  // {
  //   $redirect_uri = urlencode("http://ahgmnt.natappfree.cc/wewhat/huodong.Ceshi/index");
  //   $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=100#wechat_redirect';
  //   $url = sprintf($url,Config::get('wewhat.APPID'),$redirect_uri);
  //   return redirect($url);
  // }

  public function power()
  {
    $http = new HttpRequest();
    $code = input('get.code');
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
    $url = sprintf($url,Config::get('wewhat.APPID'),Config::get('wewhat.SECRET'),$code);
    $json = $http->http_request($url);
    $arr = json_decode($json,true);
    $access_token = $arr['access_token'];
    $openid = $arr['openid'];
    
    // 拉取用户信息
    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN';
    $url = sprintf($url,$access_token,$openid);
    $json = $http->http_request($url);
    $userinfo = json_decode($json,true);
    $userinfo['openid'] = $openid;
    $model = new fxuserModel();
    $res = $model->where('openid','=',$openid)->find();
    if (!$res) {
      $model->allowField(true)->save($userinfo);
    }
    return $userinfo;
  }

}

?>